<template>
  <div class="app-container">
    <content-block title="基本信息" v-loading="baseLoading">
      <el-row :gutter="32">
        <el-col :span="8" class="detail-item">
          <label>节点名称：</label>
          <span>{{ detail.nodeName }}</span>
        </el-col>
        <el-col :span="8" class="detail-item">
          <label>节点类型：</label>
          <span>{{ detail.nodeType === 1 ? "章鱼" : "其他" }}</span>
        </el-col>
        <el-col :span="8" class="detail-item">
          <label>节点Url：</label>
          <span>{{ detail.nodeUrl }}</span>
        </el-col>
        <el-col :span="8" class="detail-item">
          <label>节点联系人：</label>
          <span>{{ detail.nodeLinkUser }}</span>
        </el-col>
        <el-col :span="8" class="detail-item">
          <label>节点联系方式：</label>
          <span>{{ detail.nodeLinkMobile }}</span>
        </el-col>
        <el-col :span="8" class="detail-item">
          <label>节点登录账号：</label>
          <span>{{ detail.nodeLoginUser }}</span>
        </el-col>
        <el-col :span="8" class="detail-item">
          <label>登陆code：</label>
          <span>{{ detail.nodeLoginCode }}</span>
        </el-col>
        <el-col :span="8" class="detail-item">
          <label>创建人：</label>
          <span>{{ detail.createBy }}</span>
        </el-col>
        <el-col :span="8" class="detail-item">
          <label>创建时间：</label>
          <span>{{ detail.createTime }}</span>
        </el-col>
        <el-col :span="8" class="detail-item">
          <label>上架状态：</label>
          <span>{{
            detail.status === 1
              ? "上架"
              : detail.status === 0
              ? "下架"
              : detail.status === -1
              ? "未审核"
              : "已驳回"
          }}</span>
        </el-col>
      </el-row>
    </content-block>
    <content-block
      title="服务器信息"
      v-loading="serverLoading"
      :element-loading-text="loadingText"
    >
      <template #extra>
        <el-button
          size="mini"
          type="primary"
          :disabled="serverLoading"
          @click="getAskId"
          >查询</el-button
        >
        <div
          style="font-size: 12px; margin-left: 20px"
          v-if="serverDetail.taskStatus && serverDetail.taskStatus != 0"
        >
          <span>查询结果：{{ taskStatusEnum[serverDetail.taskStatus] }}，</span>
          <span> 查询耗时：{{ serverDetail.askSec }}秒</span>
          <span v-show="serverDetail.taskStatus === -2"
            >失败原因：{{ serverDetail.failReason }}</span
          >
        </div>
      </template>
      <el-table :data="nodeSearchRetList">
        <el-table-column label="服务器名称" prop="serverDevice" />
        <el-table-column label="服务器状态：" prop="serverStatus">
          <template #default="{ row }">{{
            row.serverStatus === 1 ? "在线" : "离线"
          }}</template>
        </el-table-column>
        <el-table-column label="CPU利用率：" prop="serverCpu">
          <template #default="{ row }">{{
            row.serverCpu ? `${row.serverCpu}%` : "-"
          }}</template>
        </el-table-column>
        <el-table-column label="内存利用率：" prop="serverMemory">
          <template #default="{ row }">{{
            row.serverMemory ? `${row.serverMemory}%` : "-"
          }}</template>
        </el-table-column>
        <el-table-column label="资源情况描述：" prop="serverResource">
          <template #default="{ row }">{{
            row.serverResource || "-"
          }}</template>
        </el-table-column>
      </el-table>
    </content-block>
    <content-block title="人员管理" v-loading="memberLoading">
      <template #extra>
        <el-button type="primary" @click="addUserVisible = true" size="mini"
          >创建</el-button
        >
        <el-button type="primary" @click="addVisible = true" size="mini"
        >绑定</el-button
        >
        <el-button
          type="danger"
          :disabled="!removeIds.length"
          size="mini"
          @click="handleRemove()"
          >删除</el-button
        >
      </template>
      <el-table
        ref="table"
        :data="memberList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="adminUserName" label="节点管理员" />
        <el-table-column prop="username" label="账号" />
        <el-table-column prop="createBy" label="创建人" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="action" label="操作" width="200">
          <template #default="{ row }">
            <el-button
              type="text"
              style="color: red"
              @click="handleRemove(row.id)"
              >移除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </content-block>
    <content-block title="节点任务"></content-block>
    <el-dialog :visible.sync="addVisible"    :close-on-click-modal="false" width="30vw" @close="cancelAdd">
      <el-form ref="addForm" :model="addForm">
        <el-form-item label="节点管理员" prop="adminUserId">
          <el-select v-model="addForm.adminUserId" placeholder="请选择管理员">
            <el-option
              v-for="user in allUserList"
              :key="user.userId"
              :disabled="selectedUserIdList.includes(user.userId)"
              :value="user.userId"
              :label="user.nickName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            v-model="addForm.remark"
            :maxlength="100"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAdd" :loading="addLoading"
          >确认</el-button
        >
      </template>
    </el-dialog>

<!--    新增用户-->
    <el-dialog title="创建节点管理员"    :close-on-click-modal="false" :visible.sync="addUserVisible" width="30vw" @close="cancelAddUser">
      <el-form ref="addUserForm" :model="addUserForm" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="nickName">
              <el-input v-model="addUserForm.nickName" placeholder="请输入姓名" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addUserForm.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号" prop="username">
              <el-input v-model="addUserForm.username" placeholder="请输入用户手机号" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户密码" prop="password">
              <el-input v-model="addUserForm.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="addUserVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddUser" :loading="addLoading"
          >确认</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script>
import ContentBlock from "@/components/ContentBlock";
import {
  getNodeDetail,
  getNodeMembers,
  addNodeUser,
  removeNodeUser, createNodeUser,
} from "@/api/supply";

import serverMixin from "./mixin/server";

const defaultConfirmOptions = {
  confirmButtonText: "确定",
  cancelButtonText: "取消",
  type: "warning",
};

export default {
  name: "NodeDetail",
  components: { ContentBlock },
  mixins: [serverMixin],
  data() {
    return {
      baseLoading: false,
      memberLoading: false,
      addLoading: false,
      detail: {},
      total: 0,
      memberList: [],
      removeIds: [],
      addVisible: false,
      addForm: {
        adminUserId: "",
        remark: "",
      },
      addUserVisible: false,
      addUserForm: {
        nickName: "",
        email: "",
        username: "",
        password: "",
        nodeId: null,
      },
      // 表单校验
      rules: {
        username: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { min: 11, max: 11, message: '请输入11位手机号', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' },
          { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ]
      }
    };
  },
  computed: {
    allUserList() {
      return this.$store.state.user.allUserList || [];
    },
    selectedUserIdList() {
      return this.memberList.map((i) => i.adminUserId);
    },
  },
  methods: {
    cancelAdd() {
      this.$refs.addForm.resetFields();
      this.addVisible = false;
    },
    cancelAddUser() {
      this.$refs.addUserForm.resetFields();
      this.addUserVisible = false;
    },
    confirmAddUser() {
      this.$refs.addUserForm.validate(async (valid) => {
        if (valid) {
          this.addLoading = true;
          try {
            await createNodeUser({
              ...this.addUserForm,
              nodeId: this.$route.query.id,
            });
            this.$message.success("创建成功");
            this.cancelAddUser();
            this.getMemberList();
          } finally {
            this.addLoading = false;
          }
        }
      });
    },
    confirmAdd() {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          this.addLoading = true;
          try {
            await addNodeUser({
              ...this.addForm,
              nodeId: this.$route.query.id,
            });
            this.$message.success("添加成功");
            this.cancelAdd();
            this.getMemberList();
          } finally {
            this.addLoading = false;
          }
        }
      });
    },
    async globalConfirmModal({
      title = "提示",
      content = "确定要删除吗？",
      options,
      callbackFunc,
    }) {
      await this.$confirm(
        content,
        title,
        Object.assign({}, defaultConfirmOptions, options)
      );
      typeof callbackFunc === "function" && callbackFunc();
    },
    handleRemove(id) {
      const ids = id ? [id] : this.removeIds;
      this.globalConfirmModal({
        callbackFunc: async () => {
          await removeNodeUser({ ids: ids.join(",") });
          this.$message.success("删除成功");
          this.getMemberList();
        },
      });
    },
    handleSelectionChange(selection) {
      this.removeIds = selection.map((item) => item.id);
    },
    async getDetail() {
      this.baseLoading = true;
      try {
        const { data } = await getNodeDetail(this.$route.query.id);
        this.detail = data;
      } finally {
        this.baseLoading = false;
      }
    },
    async getMemberList() {
      this.memberLoading = true;
      try {
        const { data } = await getNodeMembers({
          pageNum: 1,
          pageSize: 999,
          nodeId: this.$route.query.id,
        });
        this.memberList = data;
      } finally {
        this.memberLoading = false;
      }
    },
  },
  created() {
    if (!this.allUserList.length) this.$store.dispatch("getAllUser");
  },
  mounted() {
    this.getDetail();
    this.getMemberList();
  },
};
</script>

<style lang="scss" scoped>
.detail-item {
  overflow: hidden;
  display: inline-flex;
  flex-wrap: wrap;
  font-size: 16px;
  margin-bottom: 16px;
  line-height: 22px;
  label {
    font-weight: normal;
  }
  span {
    flex: 1;
  }
}
</style>
